import dbl from '@/utils/dbl'
import {logout} from '@/api/login'
const user = {
    state: {
        user: {},
        roles: {},
        menus: [],
        loadMenus: false
    },

    mutations: {
        SET_USER: (state, userInfo) => {
            state.user = userInfo
        },
        SET_ROLES: (state, roles) => {
            let data = {}
            roles.forEach(item => {
                data[item] = true
            })
            state.roles = data
        },
        SET_MENU: (state, menus) => {
            state.menus = menus
        },
    },

    actions: {
        // 登出
        LogOut({commit}) {
            return new Promise((resolve, reject) => {
                logout().then(() => {
                    let lastUrl = localStorage.getItem('lastUrl')
                    if(lastUrl){
                        localStorage.clear()
                        localStorage.setItem('lastUrl',lastUrl)
                    } else {
                        localStorage.clear()
                    }
                    location.href = '/platform/login'
                })
            })
        },
        initUser({commit}) {
            let menus = dbl.get('menus')
            let user = dbl.get('user')
            let roles = dbl.get('roles')
            if (menus && user && roles) {
                commit('SET_USER', user)
                commit('SET_ROLES', roles)
                commit('SET_MENU', menus)
            }
        }
    }
}

export default user
